package com.t.bricks.bussiness.util.recharge;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import com.github.wxpay.sdk.WXPayConfig;
import com.t.bricks.model.Log;

/**
 * 微信支付配置工具
 * @author HuangXinBian
 * @DateTime 2021年9月19日 上午10:38:48
 */
public class WXPayConfigCustom implements WXPayConfig {
	
	private byte[] certData;
	
	/**
	 * 微信公众号的appid,同时设置在微信平台
	 */
	private String appId;
	
	/**
	 * 微信商户ID,同时设置在微信平台
	 */
	private String mchId;
	
	/**
	 * 微信商户API密钥,同时设置在微信平台
	 */
	private String mchKey;

	@Override
	public String getAppID() {
		return appId;
	}

	@Override
	public String getMchID() {
		return mchId;
	}

	@Override
	public String getKey() {
		return mchKey;
	}

	@Override
	public InputStream getCertStream() {
		if (certData.length < 1) {
			return null;
		}
		
		return new ByteArrayInputStream(certData);
	}

	@Override
	public int getHttpConnectTimeoutMs() {
		return 0;
	}

	@Override
	public int getHttpReadTimeoutMs() {
		return 0;
	}

	/**
	 * 
	 */
	public WXPayConfigCustom() {
		super();
	}

	/**
	 * @param appId
	 * @param mchId
	 * @param mchKey
	 */
	public WXPayConfigCustom(String appId, String mchId, String mchKey) {
		super();
		this.appId = appId;
		this.mchId = mchId;
		this.mchKey = mchKey;
		
		String path = (System.getProperty("user.dir") + "/data/front/apiclient_cert.p12").replaceAll("\\\\", "/");
		File file = new File(path);
		if (!file.exists()) {
			Log.error("微信支付证书不在指定目录:", path);
			return;
		}
		
		try (
				InputStream targetStream = new FileInputStream(file)
		) {
			certData = IOUtils.toByteArray(targetStream);
		} catch (Exception e) {
			Log.error("读取微信支付证书异常:", e.getMessage());
		}
	}
	
}
